package edu.uoc.tdp.pac4.client.Academic;

import java.awt.*;
import java.awt.event.*;
import java.rmi.RemoteException;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import edu.uoc.tdp.pac4.beans.Course;
import edu.uoc.tdp.pac4.beans.Group;
import edu.uoc.tdp.pac4.beans.Registration;
import edu.uoc.tdp.pac4.beans.Shift;
import edu.uoc.tdp.pac4.client.ClientConnectionHelper;
import edu.uoc.tdp.pac4.common.AcademicManagementInterface;
import edu.uoc.tdp.pac4.common.util.LanguageUtils;
import javax.swing.DefaultComboBoxModel;

/**
 * Creates a JFrame to update a Registration
 * 
 * @author Laia
 * 
 */

public class Registration_AcceptRegistration extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	AcademicManagementInterface academicManagement;
	ClientConnectionHelper connectionHelper_;

	private JPanel contentPane;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField textField_2;
	private JTextField textField_3;
	private JTextField textFieldMorning;
	private JComboBox<Shift> comboBoxTorn;
	private JTextField textFieldAfternoon;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private JRadioButton rbtAccepted;
	private JRadioButton rbtPending;
	private JRadioButton rbtBaja;
	private boolean hihagrup = false;

	/**
	 * Creates de JFrame to update the Group group
	 * 
	 * @param group
	 */
	public Registration_AcceptRegistration(final Registration registration,
			final Group group, ClientConnectionHelper connectionHelper) {

		connectionHelper_ = connectionHelper;
		academicManagement = connectionHelper_.getAcademicManager();

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 447);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JButton btnDesar = new JButton(
				LanguageUtils.getMessage("client.management.button.save"));
		btnDesar.setBounds(10, 375, 89, 23);
		contentPane.add(btnDesar);
		btnDesar.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					update(registration, group);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});

		JButton btnCancellar = new JButton(
				LanguageUtils.getMessage("client.management.button.cancel"));
		btnCancellar.setBounds(335, 375, 89, 23);
		contentPane.add(btnCancellar);
		btnCancellar.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});

		JPanel panel = new JPanel();
		panel.setBounds(10, 36, 414, 211);
		contentPane.add(panel);
		panel.setLayout(null);

		JLabel lblId = new JLabel(
				LanguageUtils.getMessage("client.management.reg.id"));
		lblId.setBounds(10, 10, 129, 14);
		panel.add(lblId);

		JLabel lblNomStudent = new JLabel(
				LanguageUtils.getMessage("client.management.reg.student"));
		lblNomStudent.setBounds(10, 45, 129, 14);
		panel.add(lblNomStudent);

		JLabel lblGroup = new JLabel(
				LanguageUtils.getMessage("client.management.reg.group"));
		lblGroup.setBounds(10, 80, 107, 14);
		panel.add(lblGroup);

		textField_3 = new JTextField();
		textField_3.setForeground(Color.DARK_GRAY);
		textField_3.setEditable(false);
		textField_3.setColumns(10);
		textField_3.setBounds(149, 7, 37, 20);
		textField_3.setText(registration.getRegistrationId() + "");
		panel.add(textField_3);

		JLabel availableSpots = new JLabel(
				LanguageUtils.getMessage("client.management.reg.available"));
		availableSpots.setBounds(10, 155, 119, 14);
		panel.add(availableSpots);

		JLabel Morning = new JLabel(
				LanguageUtils.getMessage("client.management.reg.morning"));
		Morning.setBounds(149, 155, 79, 14);
		panel.add(Morning);

		textField = new JTextField();
		textField.setForeground(Color.DARK_GRAY);
		textField.setEditable(false);
		textField.setColumns(10);
		textField.setBounds(149, 42, 177, 20);
		textField.setText(registration.getUserId() + "");
		panel.add(textField);

		textField_1 = new JTextField();
		textField_1.setForeground(Color.DARK_GRAY);
		textField_1.setEditable(false);
		textField_1.setColumns(10);
		textField_1.setBounds(149, 77, 177, 20);
		textField_1.setText(group.getName() + "");
		panel.add(textField_1);

		textField_2 = new JTextField();
		textField_2.setForeground(Color.DARK_GRAY);
		textField_2.setEditable(false);
		textField_2.setColumns(10);
		textField_2.setBounds(149, 112, 177, 20);
		textField_2.setText(group.getShift() + "");
		panel.add(textField_2);

		textFieldMorning = new JTextField();
		textFieldMorning.setForeground(Color.DARK_GRAY);
		textFieldMorning.setEditable(false);
		textFieldMorning.setColumns(10);
		textFieldMorning.setBounds(238, 152, 26, 20);
		panel.add(textFieldMorning);

		textFieldAfternoon = new JTextField();
		textFieldAfternoon.setForeground(Color.DARK_GRAY);
		textFieldAfternoon.setEditable(false);
		textFieldAfternoon.setColumns(10);
		textFieldAfternoon.setBounds(238, 183, 26, 20);
		panel.add(textFieldAfternoon);

		if (group.getShift().equals(Shift.MORNING)) {
			textFieldMorning.setText(group.getAvailableSpots() + "");
			Group otherGroup = null;
			;
			try {
				otherGroup = academicManagement.findGroupByNameAndShift(
						group.getName(), Shift.AFTERNOON);
			} catch (RemoteException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			if (otherGroup == null) {
				textFieldAfternoon.setText("0");
			} else {
				hihagrup = true;
				textFieldAfternoon.setText(otherGroup.getAvailableSpots() + "");
			}
		}

		if (group.getShift().equals(Shift.AFTERNOON)) {
			textFieldAfternoon.setText(group.getAvailableSpots() + "");
			Group otherGroup = null;
			;
			try {
				otherGroup = academicManagement.findGroupByNameAndShift(
						group.getName(), Shift.MORNING);
			} catch (RemoteException e1) {
				e1.printStackTrace();
			}

			if (otherGroup == null) {
				textFieldMorning.setText("0");
			} else {
				hihagrup = true;
				textFieldMorning.setText(otherGroup.getAvailableSpots() + "");
			}

		}

		JLabel tarde = new JLabel(
				LanguageUtils.getMessage("client.management.reg.afternoon"));
		tarde.setBounds(149, 183, 79, 14);
		panel.add(tarde);

		JLabel turno = new JLabel(
				LanguageUtils.getMessage("client.management.button.shift"));
		turno.setBounds(10, 115, 107, 14);
		panel.add(turno);

		JLabel lblGestiDeGrups = new JLabel(
				LanguageUtils.getMessage("client.management.title.acceptReg"));
		lblGestiDeGrups.setBounds(10, 11, 321, 14);
		contentPane.add(lblGestiDeGrups);

		JPanel panel_1 = new JPanel();
		panel_1.setLayout(null);
		panel_1.setBounds(10, 258, 414, 90);
		contentPane.add(panel_1);

		JLabel label_1 = new JLabel(
				LanguageUtils.getMessage("client.management.reg.change.shift"));
		label_1.setBounds(10, 24, 130, 14);
		panel_1.add(label_1);

		comboBoxTorn = new JComboBox<Shift>();
		DefaultComboBoxModel<Shift> model = new DefaultComboBoxModel<Shift>();
		model.addElement(null);
		model.addElement(Shift.MORNING);
		model.addElement(Shift.AFTERNOON);
		comboBoxTorn.setModel(model);
		comboBoxTorn.setBounds(150, 21, 178, 20);
		panel_1.add(comboBoxTorn);

		JLabel estatus = new JLabel(
				LanguageUtils.getMessage("client.management.button.regStatus"));
		estatus.setBounds(10, 65, 121, 14);
		panel_1.add(estatus);

		rbtAccepted = new JRadioButton(
				LanguageUtils.getMessage("client.management.button.accepted"));
		rbtAccepted.setBounds(147, 65, 93, 23);

		panel_1.add(rbtAccepted);
		buttonGroup.add(rbtAccepted);

		rbtPending = new JRadioButton(
				LanguageUtils.getMessage("client.management.button.pending"));
		rbtPending.setBounds(241, 65, 87, 23);
		panel_1.add(rbtPending);
		buttonGroup.add(rbtPending);

		rbtBaja = new JRadioButton(
				LanguageUtils.getMessage("client.management.button.notActive"));
		rbtBaja.setBounds(327, 65, 81, 23);
		panel_1.add(rbtBaja);
		buttonGroup.add(rbtBaja);

		switch (registration.getStatus()) {
		case 0:
			rbtPending.setSelected(true);
			break;
		case 1:
			rbtAccepted.setSelected(true);
			break;
		case 2:
			rbtBaja.setSelected(true);
			break;

		}
	}

	/**
	 * Reads the information from the fields to update.
	 * 
	 * @throws Exception
	 * 
	 */
	public void update(Registration registration, Group group) throws Exception {

		// Gets the shift and checks whether a change of group is requested
		Shift shift = null;
		shift = (Shift) comboBoxTorn.getSelectedItem();
		Boolean canviGroup;

		if (shift == group.getShift() || shift == null) {
			canviGroup = false;
		} else {
			canviGroup = true;
		}

		// checks whether a change of status is requested
		boolean canviStatus = false;

		int pastStatus = registration.getStatus();
		int status = pastStatus;

		int spots = 0;

		if (rbtAccepted.isSelected()) {
			status = 1;
			if (pastStatus != 1) {
				canviStatus = true;
				spots = -1;
			}
		}

		if (rbtPending.isSelected()) {
			status = 0;
			if (pastStatus != 0) {
				canviStatus = true;
			}
			if (pastStatus == 1) {
				spots = 1;
			}
		}

		if (rbtBaja.isSelected()) {
			status = 2;
			if (pastStatus != 2) {
				canviStatus = true;
			}
			if (pastStatus == 1) {
				spots = 1;
			}
		}

		if (canviStatus == false) {
			status = registration.getStatus();
		}

		// If a change of group of requested, checks whether the group exists.
		// It also checks whether there are available spots in the requested
		// group.
		// If the update is possible, it also updates the spots in the relevant
		// groups.
		if (canviGroup) {
			if (hihagrup == false) {

				JOptionPane.showMessageDialog(null, LanguageUtils
						.getMessage("client.management.error.nogrup"), "error",
						JOptionPane.ERROR_MESSAGE);
				return;
			} else {
				Group anotherGroup = academicManagement
						.findGroupByNameAndShift(group.getName(), shift);

				if (canviStatus && status == 1
						&& anotherGroup.getAvailableSpots() == 0) {
					JOptionPane.showMessageDialog(null, LanguageUtils
							.getMessage("client.management.error.nospots"),
							"error", JOptionPane.ERROR_MESSAGE);
					return;
				} else {
					int ax = JOptionPane
							.showConfirmDialog(
									null,
									LanguageUtils
											.getMessage("client.management.button.update.reg.question"));
					if (ax == JOptionPane.YES_OPTION) {

						int spotsNewGroup = anotherGroup.getAvailableSpots();
						int spotsOldGroup = group.getAvailableSpots();

						if (!canviStatus && status == 1) {
							spotsOldGroup += 1;
							spotsNewGroup -= 1;

						}

						if (canviStatus && status == 1) {
							spotsNewGroup -= 1;

						}

						if (canviStatus && pastStatus == 1) {
							spotsOldGroup += 1;

						}

						academicManagement.updateGroup(
								anotherGroup.getGroupId(), spotsNewGroup);
						academicManagement.updateGroup(group.getGroupId(),
								spotsOldGroup);

						academicManagement.updateRegistration(
								registration.getRegistrationId(), status,
								anotherGroup.getGroupId());

						JOptionPane
								.showMessageDialog(
										null,
										LanguageUtils
												.getMessage("client.management.button.reg.updated"),
										null, JOptionPane.INFORMATION_MESSAGE);
						dispose();
					}
				}
			}
		} else {
			if (canviStatus && status == 1 && group.getAvailableSpots() == 0) {
				JOptionPane.showMessageDialog(null, LanguageUtils
						.getMessage("client.management.error.nospots"),
						"error", JOptionPane.ERROR_MESSAGE);
				return;
			} else {
				if (canviStatus) {
					int ax = JOptionPane
							.showConfirmDialog(
									null,
									LanguageUtils
											.getMessage("client.management.button.update.reg.question"));
					if (ax == JOptionPane.YES_OPTION) {

						spots = spots + group.getAvailableSpots();
						academicManagement.updateGroup(group.getGroupId(),
								spots);
						academicManagement.updateRegistration(
								registration.getRegistrationId(), status,
								registration.getGroupId());
						JOptionPane
								.showMessageDialog(
										null,
										LanguageUtils
												.getMessage("client.management.button.reg.updated"),
										null, JOptionPane.INFORMATION_MESSAGE);
						dispose();
					}
				}
			}
			dispose();

		}

	}

	/**
	 * Method to fill the ComboBox for the courses a group can belong to
	 * 
	 * @param group
	 * @return
	 * @throws RemoteException
	 */
	public DefaultComboBoxModel<String> posarModel(Group group)
			throws RemoteException {
		List<Course> courses;
		courses = academicManagement.listCourses();
		DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
		model.insertElementAt(group.getName(), 0);
		for (int i = 0; i < courses.size(); i++) {
			if (!courses.get(i).getCourseName().equals(group.getName())) {
				model.addElement(courses.get(i).getCourseName());
			}
		}
		return model;

	}
}
